package com.dominator.socket;


import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.typewrap.Dtos;
import com.dominator.utils.encode.Des3Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint(value = "/watching/guaMachine/{machineId}")
@Slf4j
public class WatchingMachineWebSocket {
    //线程安全的静态变量，表示在线连接数
    private static volatile int onlineCount = 0;

    //用来存放每个客户端对应的WebSocket对象，适用于同时与多个客户端通信
    public static CopyOnWriteArraySet<WatchingMachineWebSocket> websocketSet = new CopyOnWriteArraySet<WatchingMachineWebSocket>();
    //若要实现服务端与指定客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
    public static ConcurrentHashMap<Session, Object> websocketMap = new ConcurrentHashMap<Session, Object>();

    //与某个客户端的连接会话，通过它实现定向推送(只推送给某个用户)
    private Session session;


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WatchingMachineWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WatchingMachineWebSocket.onlineCount--;
    }


    /**
     * 连接建立成功调用的方法
     *
     * @param session 可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(@PathParam("machineId") String machineId, Session session) {
        this.session = session;
        websocketSet.add(this);     //加入set中
        websocketMap.put(session, this); //加入map中
        addOnlineCount();

        //机器登陆的实现
        Dto dto = Dtos.newDto();
        dto.put("guaMachineId", machineId);
        dto.put("sessionId", session.getId());
        dto.put("router", "ApiWatchingMachineService");
        dto.put("method", "init");
        SocketMessage msg = WebSocketTools.invokeMethod(dto, session);
        //返回
        sendToSession(msg, session);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session closeSession) {
        websocketSet.remove(this); //从set中删除
        websocketMap.remove(closeSession); //从map中删除
        subOnlineCount();          //在线数减1
        //--------------群发消息(多用于聊天室场景)
        for (WatchingMachineWebSocket item : websocketSet) {
            try {
                this.session.getBasicRemote().sendText("有一连接关闭！当前在线人数为" + getOnlineCount());
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message   客户端发送过来的消息
     * @param mySession 可选的参数
     * @throws Exception
     */
    @OnMessage
    public void onMessage(String message, Session mySession) throws Exception {
        log.info("会话sessionId" + mySession.getId() + "来自客户端的消息:" + message);
        sendToSession(WebSocketTools.invokeMethod(message, mySession), mySession);

    }


    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        log.info("会话id" + session.getId());
        try {
            Object object = BeanLoader.getSpringBean("ApiWatchingMachineService");
            Class c = object.getClass();
            Method method = c.getMethod("delAllSession", String.class);
            method.invoke(object, session.getId());
        } catch (Exception e) {
            log.error("删除会话失败");
        }

    }


    //定向发送信息
    public void sendMessage(Session mySession, String message) throws IOException {
        synchronized (this) {
            WebSocketTools.sendMessage(message, mySession);
        }

    }


    public void sendToSession(SocketMessage msg, Session mySession) {
        //推送给单个客户端
        sendToSessionId(msg, mySession.getId());
    }


    public static void sendToSessionId(Object msg, String sessionId) {
        for (Session session : websocketMap.keySet()) {
            if (session.getId().equals(sessionId)) {
                WatchingMachineWebSocket item = (WatchingMachineWebSocket) websocketMap.get(session);
                try {
                    item.sendMessage(session, Des3Utils.encResponse(msg));
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("发送失败" + e.getMessage());
                }
            }
        }
    }


}


